﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Sgr.AspNetCore;

namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// ControllerBase 扩展方法
    /// </summary>
    public static class ControllerBaseExtensions
    {
        /// <summary>
        /// 自定义400结果(BadRequest)
        /// </summary>
        /// <param name="controller">控制器基类</param>
        /// <param name="message">错误消息</param>
        /// <returns>400错误结果</returns>
        public static BadRequestObjectResult CustomBadRequest(this ControllerBase controller, string? message = null)
        {
            var problemDetails = new ProblemDetails
            {
                Status = StatusCodes.Status400BadRequest,
                Title = message ?? "操作无法完成，请确认后重试",
                Type = ProblemTypes.Validation,
                Instance = controller.HttpContext.Request.Path
            };

            return controller.BadRequest(problemDetails);
        }

        /// <summary>
        /// 自定义401结果(Unauthorized)
        /// </summary>
        /// <param name="controller">控制器基类</param>
        /// <param name="message">错误消息</param>
        /// <returns>401未授权结果</returns>
        public static UnauthorizedObjectResult CustomUnauthorized(this ControllerBase controller, string? message = null)
        {
            var problemDetails = new ProblemDetails
            {
                Status = StatusCodes.Status401Unauthorized,
                Title = message ?? "您暂无权限访问此功能",
                Type = ProblemTypes.Unauthorized,
                Instance = controller.HttpContext.Request.Path
            };

            return controller.Unauthorized(problemDetails);
        }

        /// <summary>
        /// 自定义404结果(NotFound)
        /// </summary>
        /// <param name="controller">控制器基类</param>
        /// <param name="message">错误消息</param>
        /// <returns>404未找到结果</returns>
        public static NotFoundObjectResult CustomNotFound(this ControllerBase controller, string? message = null)
        {
            var problemDetails = new ProblemDetails
            {
                Status = StatusCodes.Status404NotFound,
                Title = message ?? "您所请求的资源无法找到",
                Type = ProblemTypes.NotFound,
                Instance = controller.HttpContext.Request.Path
            };

            return controller.NotFound(problemDetails);
        }
    }
}